<?php

class UserController extends Controller {

    /**
     * 权限访问控制过滤
     */
    public function filters() {
        return array(
            'accessControl',
        );
    }

    /**
     * 访问控制规则
     * 在filters里面用accessControl来调用
     */
    public function accessRules() {
        return array(
            array('allow', // 注册用户可以访问
                'actions' => array(
                    'changePwd',
                ),
                'users' => array('@'),
            ),
            array('allow', // 只有帐号为 demo 的用户可以访问
                'actions' => array('changePwd'),
                'users' => array('demo'),
            ),
            array('deny', // 禁用其他情况下的所有用户
                'users' => array('*'),
            ),
        );
    }

    /**
     * 修改密码
     */
    public function actionChangePwd() {
        $this->pageTitle = '修改密码' . $this->pageTitle;
        $this->breadcrumbs = array(
            '修改密码',
        );
        $model = User::model()->findByPk(Yii::app()->user->id);
        $model->scenario = 'resetPwd';
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-validate') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        if (isset($_POST['User']['password_new']) && isset($_POST['User']['password_current'])) {
            $result = '';
            $model->attributes = $_POST['User'];
            if ($model->validate(array('password_new', 'password_current', 'password_repeat'))) {
                $saveOk = $model->saveAttributes(array('password' => md5($_POST['User']['password_new'])));
                if ($saveOk) {
                    $result = "修改密码成功！";
                } else {
                    $result = "修改密码失败！";
                }
            } else {
                $result = "信息输入有误！";
            }
            Yii::app()->user->setFlash('cresult', $result);
        }
        $model->unsetAttributes(array('password', 'password_current', 'password_repeat'));
        $this->render('changePwd', array('model' => $model));
    }

}